#!/usr/bin/env bash
# docker registry
REGISTRY="docker-registry.easemob.com/kefu/rtc-xswitch"
# docker image version
VERSION="2.2.ca724c0"
# recorder home path of host os
REC_HOME="/data2/apps/RTC2.2.ca724c0/recorder/"
# container is worker or controller
REC_ROLE="controller"
# worker container number
WORKER_NUM=4
# container tag
REC_TAG="rec"
# controller listen address, worker will connect to this address
CTRL_ADDR="10.168.249.91:10001"

function start() {
    if [[ "$REC_ROLE" == "controller" ]]; then
        docker run --restart always -d --net=host --name "$REC_TAG-$REC_ROLE" -v /etc/localtime:/etc/localtime:ro -v "$REC_HOME":/data/ "$REGISTRY:$VERSION" recorder -listen "$CTRL_ADDR" -home "/data/" -keep 10 -id "$REC_TAG-ctl"
    elif [[ "$REC_ROLE" == "worker" ]]; then
        for (( i=1;i<=${WORKER_NUM};i++ )); do
            docker run --restart always -d --net=host --name "$REC_TAG-$REC_ROLE-$i" -v /etc/localtime:/etc/localtime:ro -v "$REC_HOME":/data/ "$REGISTRY:$VERSION" recorder -connect "$CTRL_ADDR" -home "/data/" -keep 10 -id "$REC_TAG-$REC_ROLE-$i"
        done
    fi
}

function stop() {
    local ctns="$(docker ps -f "name=$REC_TAG-$REC_ROLE" -q)"
    for id in ${ctns}; do
        docker stop "$id"
        docker rm "$id"
    done
}

function restart() {
    stop
    start
}

function upgrade() {
    local prog=$1
    if [[ -z "$prog" ]]; then
        echo "no prog"
        exit -1
    fi
    VERSION=$2
    if [[ -z "$VERSION" ]]; then
        echo "no version"
        exit -1
    fi
    docker pull "$REGISTRY:$VERSION"
    if [[ $? -ne 0 ]]; then
        echo "unable to pull $REGISTRY:$VERSION"
        exit -1
    fi
    sed -i -re "s/^VERSION=.*$/VERSION=\"$VERSION\"/" "$prog"
}


case $1 in
    restart)
        stop
        start
        ;;
    stop)
        stop
        ;;
    start)
        start
        ;;
    upgrade)
        upgrade $0 $2
        ;;
esac
